package com.spider.admin.controller.advice;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
@ResponseBody
public class SpiderExceptionHandler {


    @ExceptionHandler(SpiderException.class)
    public ResponseEntity exception(SpiderException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        ResponseEntity response=new ResponseEntity();
        response.setCode(e.getCode());
        response.setMessage(e.getMessage());
        response.setErrMessage(e.getStackMessage());
        //这里返回 HashMap ，就相当于项前端返回了一个 JSON 格式的数据
        return response;
    }
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity nullPointException(NullPointerException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        ResponseEntity response=new ResponseEntity();
        response.setCode(-1);
        response.setMessage("运行空指针异常");
        response.setErrMessage(e.getMessage());
        //这里返回 HashMap ，就相当于项前端返回了一个 JSON 格式的数据
        return response;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 获取错误信息
        String errMsg=ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error(errMsg);
        ex.printStackTrace();
        ResponseEntity response=new ResponseEntity();
        response.setCode(ResultMessage.FAILED_PARAMS_VALIDATE.getCode());
        response.setMessage(errMsg);
        response.setErrMessage(ex.getMessage());
        //这里返回 HashMap ，就相当于项前端返回了一个 JSON 格式的数据
        return response;
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity nullPointException(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        ResponseEntity response=new ResponseEntity();
        response.setCode(ResultMessage.ERROR_SERVICES.getCode());
        response.setMessage(ResultMessage.ERROR_SERVICES.getMessage());
        response.setErrMessage(e.getMessage());
        //这里返回 HashMap ，就相当于项前端返回了一个 JSON 格式的数据
        return response;
    }
}

